<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.userName"
              placeholder="请输入用户名"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="管理员名称">
            <el-input
              v-model="searchForm.managerName"
              placeholder="请输入管理员名称"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="订单ID">
            <el-input
              v-model="searchForm.orderID"
              placeholder="请输入订单ID"
              clearable
              style="width: 150px"
            />
          </el-form-item>

          <el-form-item label="支付地址">
            <el-input
              v-model="searchForm.payAddress"
              placeholder="请输入支付地址"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="接收地址">
            <el-input
              v-model="searchForm.receiveAddress"
              placeholder="请输入接收地址"
              clearable
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.state"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="等待审核" :value="0" />
              <el-option label="等待申请人确认" :value="1" />
              <el-option label="已确认" :value="2" />
              <el-option label="审核人结算确认" :value="3" />
              <el-option label="失败" :value="4" />
            </el-select>
          </el-form-item>

          <!-- 金额范围 -->
          <el-form-item label="金额范围">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-input-number
                v-model="searchForm.amount[0]"
                placeholder="最小值"
                :min="0"
                :precision="2"
                style="width: 120px"
              />
              <span>-</span>
              <el-input-number
                v-model="searchForm.amount[1]"
                placeholder="最大值"
                :min="0"
                :precision="2"
                style="width: 120px"
              />
            </div>
          </el-form-item>

          <!-- 创建时间范围 -->
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.ctimeDateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 350px"
            />
          </el-form-item>

          <!-- 汇率范围 -->
          <el-form-item label="汇率范围">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-input-number
                v-model="searchForm.rate[0]"
                placeholder="最小值"
                :min="0"
                :precision="4"
                style="width: 120px"
              />
              <span>-</span>
              <el-input-number
                v-model="searchForm.rate[1]"
                placeholder="最大值"
                :min="0"
                :precision="4"
                style="width: 120px"
              />
            </div>
          </el-form-item>

          <!-- USDT范围 -->
          <el-form-item label="USDT范围">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-input-number
                v-model="searchForm.usdt[0]"
                placeholder="最小值"
                :min="0"
                :precision="2"
                style="width: 120px"
              />
              <span>-</span>
              <el-input-number
                v-model="searchForm.usdt[1]"
                placeholder="最大值"
                :min="0"
                :precision="2"
                style="width: 120px"
              />
            </div>
          </el-form-item>

          <!-- 更新时间范围 -->
          <el-form-item label="更新时间">
            <el-date-picker
              v-model="searchForm.utimeDateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 350px"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card">
      <div>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增入金
        </el-button>
        <span>
          <!-- <span>全部金额：</span><span class="amount"></span>
        <span>完成金额：</span><span class="amount"></span>
        <span>全部金额：</span><span class="amount"></span> -->
          <span style="margin-left: 50px;">成功充值金额：</span>
          <span class="amount" style="color: red">{{ successTotal }}</span>
        </span>
      </div>
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column
          prop="orderID"
          label="订单号"
          width="180"
          align="center"
        />
        <el-table-column
          prop="amount"
          label="充值金额"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <span>{{ row.amount ? row.amount.toFixed(2) : "0.00" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="usdt" label="usdt" width="120" align="center" />
        <el-table-column
          prop="rateAmount"
          label="汇率金额"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span>{{
              row.rateAmount ? row.rateAmount.toFixed(2) : "0.00"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="payAddress"
          label="支付地址"
          width="120"
          align="center"
        />
        <el-table-column
          prop="receiveAddress"
          label="接收地址"
          width="120"
          align="center"
        />
        <el-table-column
          prop="userName"
          label="申请人"
          width="120"
          align="center"
        />
        <el-table-column
          prop="manage_name"
          label="审核人"
          width="120"
          align="center"
        />
        <!-- <el-table-column prop="arrivalAmount" label="到账金额" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.arrivalAmount ? row.arrivalAmount.toFixed(2) : '0.00' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="remark"
          label="备注"
          width="150"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="state"
          label="支付状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.state)">{{
              getStatusText(row.state)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="cTime"
          label="创建时间"
          width="180"
          align="center"
        />
        <el-table-column
          prop="uTime"
          label="更新时间"
          width="180"
          align="center"
        />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="handleOperation(row)"
              >入金操作</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增入金弹窗 -->
    <el-dialog
      v-model="addVisible"
      title="新增入金"
      width="500px"
      :before-close="handleCloseAdd"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="支付地址" prop="payAddress">
          <el-input
            v-model="addForm.payAddress"
            placeholder="请输入支付地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="USDT金额" prop="usdt">
          <el-input-number
            v-model="addForm.usdt"
            placeholder="请输入USDT金额"
            style="width: 100%"
            :precision="2"
            :step="0.01"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAdd">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmitAdd"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 入金操作弹窗 -->
    <el-dialog
      v-model="operationVisible"
      title="入金操作"
      width="500px"
      :before-close="handleCloseOperation"
    >
      <el-form
        ref="operationFormRef"
        :model="operationForm"
        :rules="operationRules"
        label-width="100px"
      >
        <el-form-item label="状态" prop="state">
          <el-radio-group
            v-model="operationForm.state"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-radio :label="0">等待审核</el-radio>
            <el-radio :label="1">等待申请人确认</el-radio>
            <el-radio :label="2">已确认</el-radio>
            <el-radio :label="3">审核人结算确认</el-radio>
            <el-radio :label="4">失败</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="operationForm.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="密钥代码" prop="secretCode">
          <el-input
            v-model="operationForm.secretCode"
            placeholder="请输入密钥代码"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseOperation">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmitOperation"
            :loading="operationLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { getUdstList, createUsdt, rejectUsdt } from "@/api/system";
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

// 响应式数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const successTotal = ref(0);

// 搜索表单
const searchForm = ref({
  userName: "",
  managerName: "",
  orderID: "",
  page: "",
  payAddress: "",
  rate: [0, 0],
  receiveAddress: "",
  size: "",
  state: null,
  amount: [0, 0],
  ctimeDateRange: [],
  usdt: [0, 0],
  utimeDateRange: [],
});

// 获取数据
const loadData = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params: any = {
      page: currentPage.value,
      size: pageSize.value,
    };

    // 添加非空的基础搜索字段
    if (searchForm.value.userName) {
      params.userName = searchForm.value.userName;
    }
    if (searchForm.value.managerName) {
      params.managerName = searchForm.value.managerName;
    }
    if (searchForm.value.orderID) {
      params.orderID = searchForm.value.orderID;
    }
    if (searchForm.value.page) {
      params.page = searchForm.value.page;
    }
    if (searchForm.value.payAddress) {
      params.payAddress = searchForm.value.payAddress;
    }
    if (searchForm.value.receiveAddress) {
      params.receiveAddress = searchForm.value.receiveAddress;
    }
    if (searchForm.value.size) {
      params.size = searchForm.value.size;
    }
    if (
      searchForm.value.state !== null &&
      searchForm.value.state !== undefined
    ) {
      params.state = searchForm.value.state;
    }

    // 处理范围字段 - 金额
    if (
      searchForm.value.amount &&
      (searchForm.value.amount[0] > 0 || searchForm.value.amount[1] > 0)
    ) {
      params.amount = searchForm.value.amount;
    }

    // 处理范围字段 - 汇率
    if (
      searchForm.value.rate &&
      (searchForm.value.rate[0] > 0 || searchForm.value.rate[1] > 0)
    ) {
      params.rate = searchForm.value.rate;
    }

    // 处理范围字段 - USDT
    if (
      searchForm.value.usdt &&
      (searchForm.value.usdt[0] > 0 || searchForm.value.usdt[1] > 0)
    ) {
      params.usdt = searchForm.value.usdt;
    }

    // 处理时间范围字段
    if (
      searchForm.value.ctimeDateRange &&
      searchForm.value.ctimeDateRange.length === 2
    ) {
      params.ctimeDateRange = searchForm.value.ctimeDateRange;
    }
    if (
      searchForm.value.utimeDateRange &&
      searchForm.value.utimeDateRange.length === 2
    ) {
      params.utimeDateRange = searchForm.value.utimeDateRange;
    }

    // 获取列表数据
    const response: any = await getUdstList(params);
    if (response.code === 0) {
      tableData.value = response.data.data || [];
      total.value = response.data.total || 0;
      successTotal.value = response.data.sumSuccess.amount || 0;
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchForm.value = {
    userName: "",
    managerName: "",
    orderID: "",
    page: "",
    payAddress: "",
    rate: [0, 0],
    receiveAddress: "",
    size: "",
    state: null,
    amount: [0, 0],
    ctimeDateRange: [],
    usdt: [0, 0],
    utimeDateRange: [],
  };
  currentPage.value = 1;
  loadData();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

// 状态处理
const getStatusType = (
  status: number
): "primary" | "success" | "info" | "warning" | "danger" => {
  //0:等待审核 1:等待申请人确认 2:已确认 3:审核人结算确认 4:失败

  switch (status) {
    case 0:
      return "primary";
    case 1:
      return "info";
    case 2:
      return "success";
    case 3:
      return "warning";
    case 4:
      return "danger";
    default:
      return "primary";
  }
};

const getStatusText = (status: number) => {
  //0:等待审核 1:等待申请人确认 2:已确认 3:审核人结算确认 4:失败
  switch (status) {
    case 0:
      return "等待审核";
    case 1:
      return "等待申请人确认";
    case 2:
      return "已确认";
    case 3:
      return "审核人结算确认";
    case 4:
      return "失败";
  }
};

// 新增入金弹窗控制
const addVisible = ref(false);
const submitLoading = ref(false);
const addFormRef = ref<FormInstance>();

// 新增入金表单数据
const addForm = reactive({
  payAddress: "",
  usdt: 0,
});

// 表单验证规则
const addRules: FormRules = {
  payAddress: [{ required: true, message: "请输入支付地址", trigger: "blur" }],
  usdt: [
    { required: true, message: "请输入USDT金额", trigger: "blur" },
    {
      validator: (_rule: any, value: number, callback: any) => {
        if (value <= 0) {
          callback(new Error("USDT金额必须大于0"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 打开新增弹窗
const handleAdd = () => {
  addVisible.value = true;
};

// 关闭新增弹窗
const handleCloseAdd = () => {
  addVisible.value = false;
  resetAddForm();
};

// 重置新增表单
const resetAddForm = () => {
  addFormRef.value?.resetFields();
  addForm.payAddress = "";
  addForm.usdt = 0;
};

// 提交新增表单
const handleSubmitAdd = async () => {
  if (!addFormRef.value) return;

  try {
    await addFormRef.value.validate();
    submitLoading.value = true;

    const response: any = await createUsdt({
      payAddress: addForm.payAddress,
      usdt: addForm.usdt,
    });

    if (response.code === 0) {
      ElMessage.success("新增成功");
      addVisible.value = false;
      resetAddForm();
      loadData(); // 刷新列表
    } else {
      ElMessage.error(response.msg || "新增失败");
    }
  } catch (error) {
    console.error("新增失败:", error);
    ElMessage.error("新增失败");
  } finally {
    submitLoading.value = false;
  }
};

// 入金操作弹窗控制
const operationVisible = ref(false);
const operationLoading = ref(false);
const operationFormRef = ref<FormInstance>();

// 入金操作表单数据
const operationForm = reactive({
  id: 0,
  state: 0,
  remark: "",
  secretCode: "",
});

// 入金操作表单验证规则
const operationRules: FormRules = {
  state: [{ required: true, message: "请选择状态", trigger: "change" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
  secretCode: [{ required: true, message: "请输入密钥代码", trigger: "blur" }],
};

// 打开入金操作弹窗
const handleOperation = (row: any) => {
  operationForm.id = row.id;
  operationForm.state = row.state || 0;
  operationForm.remark = row.remark || "";
  operationForm.secretCode = "";
  operationVisible.value = true;
};

// 关闭入金操作弹窗
const handleCloseOperation = () => {
  operationVisible.value = false;
  resetOperationForm();
};

// 重置入金操作表单
const resetOperationForm = () => {
  operationFormRef.value?.resetFields();
  operationForm.id = 0;
  operationForm.state = 0;
  operationForm.remark = "";
  operationForm.secretCode = "";
};

// 提交入金操作表单
const handleSubmitOperation = async () => {
  if (!operationFormRef.value) return;

  try {
    await operationFormRef.value.validate();
    operationLoading.value = true;

    const response: any = await rejectUsdt({
      id: operationForm.id,
      state: operationForm.state,
      remark: operationForm.remark,
      secretCode: operationForm.secretCode,
    });

    if (response.code === 0) {
      ElMessage.success("操作成功");
      operationVisible.value = false;
      resetOperationForm();
      loadData(); // 刷新列表
    } else {
      ElMessage.error(response.msg || "操作失败");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  } finally {
    operationLoading.value = false;
  }
};

// 入金操作（保留原有代码兼容性）
// 初始化
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  font-weight: bold;
}
.search-card {
  margin-bottom: 20px;
}
</style>
